package com.test.acceltest;

import java.text.DecimalFormat;

import android.app.Activity;
import android.os.Bundle;
import android.hardware.*;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.ToggleButton;
import android.os.Handler;
import com.test.acceltest.Gesture;
import com.test.acceltest.R;
import com.eqsoft.gesturerecognition.*;

public class AccelTest22 extends Activity {
	
	private SensorManager sensorManager;
	private float[] accel = new float[3];
	private boolean recording = false;
	private Gesture gest;
	
	private SensorEventListener sensorListener = new SensorEventListener()
	{	
		public void onSensorChanged(SensorEvent event) {
			accel = event.values;
		}
		
		public void onAccuracyChanged(Sensor sensor, int accuracy) {
			
		}
	};
	
	private Handler handler = new Handler();
	DecimalFormat round = new DecimalFormat("#.##");
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        sensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
        sensorManager.registerListener(sensorListener, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
        
        setContentView(R.layout.main);
        
        final TextView tv = (TextView)findViewById(R.id.textView1);
        tv.setText("Press to begin recording");

        final ToggleButton tb = (ToggleButton)findViewById(R.id.toggleButton1);
        tb.setOnClickListener(new OnClickListener()
        {
        	@Override
        	public void onClick(View v)
        	{
        		if (tb.isChecked())
        		{
        			gest = new Gesture();
        			handler.postDelayed(recordTask, 100);
        			recording = true;
        			tv.setText("Recording");
        		}
        		else
        		{
        			recording = false;
        			tv.setText(gest.toString());
        			Log.v("Vector", gest.toString());
        		}
        	}
        });
    }
    
    @Override
    protected void onResume() {
      super.onResume();
      sensorManager.registerListener(sensorListener, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
    }   
    @Override
    protected void onStop() {
      sensorManager.unregisterListener(sensorListener);
      super.onStop();
    }
   
    private Runnable recordTask = new Runnable() {
		public void run() {
			gest.add(accel);
			if(recording)
				handler.postDelayed(this, 100);
		}
	};
}